<template>
  <div class="app-container">
    <!-- 搜索筛选栏 -->
    <div class="search-bar">
      <el-form ref="queryFormRef" class="m-r-8" :model="queryParams" :inline="true">
        <el-form-item>
          <el-select
            v-model="queryParams.categoryId"
            placeholder="请选择分类"
            clearable
            filterable
            class="m-r-8"
          >
            <el-option
              v-for="category in categoryOptions"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="queryParams.titleKeywords"
            placeholder="请输入标题或用户名称"
            clearable
            class="m-r-8"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 社区动态列表 -->
    <el-card shadow="never">
      <el-table v-loading="loading" :data="currentPageData" highlight-current-row row-key="id">
        <el-table-column label="序号" align="center" width="80">
          <template #default="scope">
            {{ (pagination.currentPage - 1) * pagination.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="标题" align="center">
          <template #default="scope">
            {{ scope.row.title }}
          </template>
        </el-table-column>
        <el-table-column label="用户名称" align="center">
          <template #default="scope">
            {{ scope.row.nickname }}
          </template>
        </el-table-column>
        <el-table-column label="收藏数" align="center" width="120">
          <template #default="scope">
            {{ scope.row.collect || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="点赞数" align="center" width="120">
          <template #default="scope">
            {{ scope.row.upvote || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="发布时间" align="center">
          <template #default="scope">
            {{ scope.row.releaseTime }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.state === 1" type="success">正常</el-tag>
            <el-tag v-else type="info">屏蔽</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="default"
              icon="Edit"
              @click.stop="handleViewDetail(scope.row.id)"
            >
              查看详情
            </el-button>
            <el-button
              :type="scope.row.state === 1 ? 'danger' : 'warning'"
              link
              size="default"
              :icon="scope.row.state === 1 ? 'Bottom' : 'Top'"
              @click.stop="handleStatusChange(scope.row)"
            >
              {{ scope.row.state === 1 ? "屏蔽" : "恢复" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination p-8">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗（含评论区） -->
    <el-dialog v-model="detailVisible" title="动态详情" width="600px" @close="handleCloseDetail">
      <div v-if="currentDetail" class="detail-content">
        <!-- 动态信息 -->
        <div class="dynamic-header">
          <div class="user-info">
            <!-- 修复：替换为稳定的默认头像地址 -->
            <img :src="currentDetail.avatar" alt="用户头像" class="avatar" />
            <div class="user-meta">
              <span class="username">{{ currentDetail.nickname }}</span>
              <span class="publish-time">{{ currentDetail.releaseTime }}</span>
            </div>
          </div>
          <h3 class="dynamic-title">{{ currentDetail.title }}</h3>
          <p class="dynamic-desc">{{ currentDetail.content }}</p>
          <div class="stats">
            <span>{{ currentDetail.collect || 0 }} 收藏</span>
            <span>{{ currentDetail.upvote || 0 }} 点赞</span>
          </div>
        </div>

        <!-- 评论区 -->
        <div class="comment-section">
          <h4 class="comment-title">评论 ({{ commentList.length }})</h4>
          <div v-for="comment in commentList" :key="comment.id" class="comment-item">
            <!-- 修复：替换为稳定的默认头像地址 -->
            <img :src="comment.avatar" alt="评论者头像" class="comment-avatar" />
            <div class="comment-info">
              <div class="comment-main">
                <div class="comment-username">{{ comment.nickname }}</div>
                <p class="comment-content">{{ comment.communityComment }}</p>
              </div>
              <div class="comment-meta">
                <span class="comment-time">{{ comment.publishDate }}</span>
                <el-button
                  link
                  size="small"
                  class="delete-comment"
                  @click="handleDeleteComment(comment.id!)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import http from "@/http"; // 引入http模块

// 定义后端模型对应的TypeScript接口
interface CommunityInfo {
  id?: string;
  userId?: string;
  title?: string;
  upvote?: number;
  collect?: number;
  nickname?: string;
  content?: string;
  releaseTime?: string;
  categoryId?: string;
  state: number;
  avatar?: string;
}

interface CommunityCommentInfo {
  id?: string;
  circleId?: string;
  userId?: string;
  avatar?: string;
  nickname?: string;
  publishDate?: string;
  communityComment?: string;
}

interface CategoryOption {
  id: string;
  name: string;
}

interface Pagination {
  currentPage: number;
  pageSize: number;
  total: number;
}

// 状态管理
const loading = ref(false);
const detailVisible = ref(false);
const currentDetail = ref<CommunityInfo | null>(null);
const commentList = ref<CommunityCommentInfo[]>([]);
const categoryOptions = ref<CategoryOption[]>([]);
const communityList = ref<CommunityInfo[]>([]);

// 分页配置
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 5,
  total: 0,
});

// 当前页数据
const currentPageData = computed(() => {
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize;
  const endIndex = startIndex + pagination.pageSize;
  return communityList.value.slice(startIndex, endIndex);
});

// 搜索参数
const queryParams = reactive({
  categoryId: "",
  titleKeywords: "",
});

// 初始化加载数据
onMounted(() => {
  loadCategoryOptions();
  handleQuery();
});

// 加载分类选项
async function loadCategoryOptions() {
  try {
    loading.value = true;
    const response = await http.getCategoryList();
    const categoryData = response.data || response;
    categoryOptions.value = categoryData.map((item: any) => ({
      id: item.id,
      name: item.name,
    }));
  } catch (error) {
    ElMessage.error("加载分类失败");
    console.error("加载分类错误:", error);
  } finally {
    loading.value = false;
  }
}

// 分页事件
function handleSizeChange(size: number) {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  handleQuery();
}

function handleCurrentChange(page: number) {
  pagination.currentPage = page;
  handleQuery();
}

// 调用接口获取社区列表
async function handleQuery() {
  try {
    loading.value = true;
    const response = await http.getCommunityList(queryParams.titleKeywords, queryParams.categoryId);
    const communityData = response.data || response;
    communityList.value = communityData.map((item: any) => ({
      id: item.id,
      userId: item.userID,
      title: item.title,
      upvote: item.upvote,
      collect: item.collect,
      nickname: item.nickname,
      content: item.content,
      releaseTime: item.releaseTime,
      categoryId: item.categoryID,
      state: item.state,
      avatar: item.avatar,
    }));
    pagination.total = communityList.value.length;
  } catch (error) {
    ElMessage.error("获取社区列表失败");
    console.error("获取社区列表错误:", error);
  } finally {
    loading.value = false;
  }
}

// 查看详情
async function handleViewDetail(id: string) {
  try {
    loading.value = true;
    currentDetail.value = communityList.value.find((item) => item.id === id) || null;

    if (currentDetail.value?.id) {
      const commentResponse = await http.getCommentList(currentDetail.value.id);
      const commentData = commentResponse.data || commentResponse;
      commentList.value = commentData.map((item: any) => ({
        id: item.id,
        circleId: item.circleId,
        userId: item.userID,
        avatar: item.avatar,
        nickname: item.nickname,
        publishDate: item.publishDate,
        communityComment: item.communityComment,
      }));
    }
    detailVisible.value = true;
  } catch (error) {
    ElMessage.error("获取详情失败");
    console.error("获取详情错误:", error);
  } finally {
    loading.value = false;
  }
}

// 关闭详情弹窗
function handleCloseDetail() {
  currentDetail.value = null;
  commentList.value = [];
  detailVisible.value = false;
}

// 变更动态状态
async function handleStatusChange(row: CommunityInfo) {
  const action = row.state === 1 ? "屏蔽" : "恢复";
  try {
    await ElMessageBox.confirm(`确定要${action}动态【${row.title}】吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: row.state === 1 ? "warning" : "info",
    });

    await http.changeCommunityState(row.id!);
    ElMessage.success(`${action}成功`);
    handleQuery();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`${action}失败`);
      console.error(`${action}错误:`, error);
    }
  }
}

// 删除评论
async function handleDeleteComment(commentId: string) {
  try {
    await ElMessageBox.confirm("确定要删除这条评论吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await http.deleteComment(commentId);
    ElMessage.success("评论删除成功");

    if (currentDetail.value?.id) {
      const commentResponse = await http.getCommentList(currentDetail.value.id);
      const commentData = commentResponse.data || commentResponse;
      commentList.value = commentData.map((item: any) => ({
        id: item.id,
        circleId: item.circleId,
        userId: item.userID,
        avatar: item.avatar,
        nickname: item.nickname,
        publishDate: item.publishDate,
        communityComment: item.communityComment,
      }));
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除评论失败");
      console.error("删除评论错误:", error);
    }
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.app-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  float: right;
}

.detail-content {
  padding: 20px;
}

.dynamic-header {
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  margin-right: 10px;
  border-radius: 50%;
}

.user-meta .username {
  display: block;
  font-weight: bold;
}

.user-meta .publish-time {
  font-size: 12px;
  color: #999;
}

.dynamic-title {
  margin-bottom: 10px;
  font-size: 18px;
}

.dynamic-desc {
  margin-bottom: 10px;
  color: #666;
  white-space: pre-line;
}

.stats {
  display: flex;
  gap: 15px;
  color: #999;
}

.comment-section {
  padding-top: 16px;
  margin-top: 16px;
  border-top: 1px solid #ebeef5;
}

.comment-title {
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.comment-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.comment-avatar {
  flex-shrink: 0;
  width: 36px;
  height: 36px;
  margin-right: 12px;
  border-radius: 50%;
}

.comment-info {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.comment-main {
  display: flex;
  flex-direction: column;
  margin-bottom: 4px;
}

.comment-username {
  margin-bottom: 4px;
  font-size: 13px;
  font-weight: 500;
  color: #606266;
}

.comment-content {
  margin: 0;
  font-size: 12px;
  line-height: 1.4;
  color: #909399;
  white-space: pre-line;
}

.comment-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  color: #c0c4cc;
}

.comment-time {
  margin-right: 16px;
}

.delete-comment {
  padding: 0;
  color: #f56c6c;
}

.delete-comment:hover {
  color: #f78989;
}
</style>
